package com.java.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wangning
 * @date 2023/5/16 09:36
 * 阻塞队列实现生产者消费者
 * Volatile/CAS/atomic/BlockQueue/线程交互
 */
public class ProdConsumerBlockQueueDemo {
    public static void main(String[] args) {
        MySource mySource = new MySource(new ArrayBlockingQueue<>(10));
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t 生产线程启动");
            try {
                mySource.myProd();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "Prod").start();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t 消费线程启动");
            try {
                mySource.myConsumer();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "Consumer").start();
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println();
        System.out.println();
        System.out.println("5秒钟到，大老板main线程叫停，活动结束");
        mySource.stop();

    }

}
class MySource {
    private volatile boolean flag = true;//默认开启，进行生产+消费
    private AtomicInteger atomicInteger = new AtomicInteger();
    BlockingQueue<String> blockingQueue = null;
    //高手在构造中都是传递的接口，而不是传递类，例如这里，不传递ArrayBlockingQueue等实现类，而是传递接口
    public MySource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println(blockingQueue.getClass().getName());//打印日志，查看传递的是谁，是那个实现类
    }

    public void myProd() throws Exception {
        String data = null;
        boolean retValue;
        while (flag) {
            data = atomicInteger.incrementAndGet() + "";
            retValue = blockingQueue.offer(data, 2, TimeUnit.SECONDS);
            if(retValue) {
                System.out.println(Thread.currentThread().getName() + "\t 插入" + data + "成功");
            } else {
                System.out.println(Thread.currentThread().getName() + "\t 插入" + data + "失败");
            }
            TimeUnit.SECONDS.sleep(1);

        }
        System.out.println(Thread.currentThread().getName() + "\t 大老板叫停，表示flag=false，生产结束");
    }

    public void myConsumer() throws Exception {
        String result;
        while (flag) {
            result = blockingQueue.poll(2, TimeUnit.SECONDS);
            if (null == result || result.equalsIgnoreCase("")) {
                flag = false;
                System.out.println(Thread.currentThread().getName() + "\t 超过2秒钟没有取到蛋糕，消费退出");
                return;
            }

            System.out.println(Thread.currentThread().getName() + "\t 消费队列" + result + "成功");
        }
    }
    public void stop() {
        this.flag = false;
    }


}




